package com.zff.rental;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.text.csv.CsvReader;
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.crypto.SecureUtil;
import com.zff.rental.entity.apartment.DeviceDictEntity;
import com.zff.rental.entity.user.AdministratorEntity;
import com.zff.rental.entity.user.UserEntity;
import com.zff.rental.repository.apartment.DeviceDictRepository;
import com.zff.rental.repository.user.AdministratorRepository;
import com.zff.rental.repository.user.UserRepository;
import com.zff.rental.service.user.UserServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.List;


/**
 * 应用启动后初始化数据库数据
 *
 * @author HCY
 */
@Component
@Slf4j
public class InitData implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext applicationContext = event.getApplicationContext();
        addSystemAdministrator(applicationContext);
        addDeviceDictData(applicationContext);
    }

    /**
     * 添加系统管理员
     */
    private void addSystemAdministrator(ApplicationContext applicationContext) {
        UserRepository userRepository = applicationContext.getBean(UserRepository.class);
        if (userRepository.count() > 0) {
            return;
        }
        UserEntity user = new UserEntity();
        user.setAccountName("hbz");
        user.setNickname("何必知");
        user.setPhone("15986241710");
        user.setGender(1);
        user.setDescription("我是系统超级管理员");
        user.setBirthday(LocalDate.of(1994, 2, 22));

        UserServer.addSaltPassword(user, SecureUtil.md5("he123456"));

        user = userRepository.save(user);
        AdministratorRepository administratorRepository = applicationContext.getBean(AdministratorRepository.class);
        administratorRepository.save(new AdministratorEntity(user.getUserId()));
    }

    /**
     * 初始化家电设备数据
     */
    private void addDeviceDictData(ApplicationContext applicationContext) {
        DeviceDictRepository deviceDictRepository = applicationContext.getBean(DeviceDictRepository.class);
        if (deviceDictRepository.count() > 0) {
            return;
        }
        long startTime = System.currentTimeMillis();
        final List<DeviceDictEntity> list = getCsvObj("init_db/apa_dict_device.csv", DeviceDictEntity.class);
        deviceDictRepository.saveAll(list);
        log.info("批量保存家电设备，执行耗时：{}", System.currentTimeMillis() - startTime);
    }

    public <T> List<T> getCsvObj(String name, Class<T> clazz) {
        final CsvReader reader = CsvUtil.getReader();
        String s = ResourceUtil.readUtf8Str(name);
        return reader.read(s, clazz);
    }
}
